import requests
from datetime import datetime, timedelta

class NasaPowerHourlyFetcher:
    BASE_URL = "https://power.larc.nasa.gov/api/temporal/hourly/point"

    def __init__(self, latitude, longitude, parameter="ALLSKY_SFC_SW_DWN", community="RE"):
        self.latitude = latitude
        self.longitude = longitude
        self.parameter = parameter
        self.community = community

    def fetch_day(self, date_str):
        """请求某一天的数据，date_str格式：'YYYYMMDD'"""
        params = {
            "parameters": self.parameter,
            "community": self.community,
            "longitude": self.longitude,
            "latitude": self.latitude,
            "start": date_str,
            "end": date_str,
            "format": "JSON",
        }
        resp = requests.get(self.BASE_URL, params=params)
        resp.raise_for_status()
        data = resp.json()
        # 取出小时数据，路径大致是 data['properties']['parameter'][parameter]
        hourly_data = data.get("properties", {}).get("parameter", {}).get(self.parameter, {})
        return hourly_data

    def fetch_range(self, start_date, end_date):
        """
        获取start_date到end_date日期区间内所有小时数据
        start_date, end_date 类型为 datetime.date 或 datetime.datetime
        返回字典：{ 'YYYYMMDDHH': value, ... }
        """
        if isinstance(start_date, datetime):
            start_date = start_date.date()
        if isinstance(end_date, datetime):
            end_date = end_date.date()

        result = {}
        current_date = start_date
        while current_date <= end_date:
            date_str = current_date.strftime("%Y%m%d")
            day_data = self.fetch_day(date_str)
            # day_data格式：{'00': val, '01': val, ... '23': val}
            # 转成 'YYYYMMDDHH' 键格式方便合并
            for hour, value in day_data.items():
                key = f"{date_str}{hour}"
                result[key] = value
            current_date += timedelta(days=1)
        return result


# 使用示例
if __name__ == "__main__":
    fetcher = NasaPowerHourlyFetcher(latitude=40.456720, longitude=115.974940)
    # 固定查询日期为2025年1月1日
    start = datetime.strptime("20250321", "%Y%m%d")
    end = start  # 单天查询

    data = fetcher.fetch_range(start, end)

    # 打印部分数据示例
    for k in sorted(data.keys()):
        print(k, data[k])
